<?php

namespace App\Inputs;

use App\Traits\VerifyFrontEndParameters;
use JetBrains\PhpStorm\ArrayShape;

class PublishRecruitInput
{
    /*public int $id;
    public int $userId;
    public string $title;
    public string $recruitDesc;
    public string $contactName;
    public string $contactPhone;
    public string $salaryInfo;
    public int $recruitCateId;
    public string $recruitCateName;
    public string $address;
    public string $addressDetail;
    public float $latitude;
    public float $longitude;

    public function rules()
    {
        return [
            "id"                => "present",
            "user_id"           => "required|integer",
            "title"             => "present|string",
            "recruit_desc"      => "required|string",
            "contact_name"      => "required|string",
            "contact_phone"     => "required|string",
            "salary_info"       => "required|json",
            "recruit_cate_id"   => "required|integer",
            "recruit_cate_name" => "required|string",
            "image"             => "present|max:255",
            "address"           => "required|string",
            "address_detail"    => "required|string",
            "latitude"          => "required|decimal:0,6",
            "longitude"         => "required|decimal:0,6",
        ];
    }*/

    use VerifyFrontEndParameters;

    // 这里如果声明了数据类型，使用 get_object_vars 方法是获取不到的
    // public string $addressDetail;
    public $address_detail;

    public function rules()
    {
        return [
            'address_detail' => 'required|string'
        ];
    }

    public function fill()
    {
        $inputs = request()->input();
        $this->check($inputs, $this->rules());

        $objAttrInfo = get_object_vars($this);
        $attrKeys = array_keys($objAttrInfo);
        collect($inputs)->map(function ($value, $key) use ($attrKeys) {
            if (in_array($key, $attrKeys)) {
                $this->$key = $value;
            }
        });

        // 分析代码发现这样好麻烦。为了不增加那么多繁琐的处理步骤，将当前类的属性不声明数据类型并且使用下划线方式定义名称。
        // 1. 因为类里定义的属性是驼峰类型，而前端传递的是下划线类型，所以要进行一次转换
        /*$inputKeys = array_keys($inputs);
        $inputKeys = array_map('snakeToCamel', $inputKeys);
        $inputs = array_combine($inputKeys, $inputs);

        // 2. 定义属性的时候声明了数据类型，用 get_object_vars 的方式获取不到，得使用反射得方式
        $obj = new ReflectionClass($this);
        // getProperties(ReflectionProperty::IS_PUBLIC) 方法里可以接受参数，比如这个就是只获取 public 类型的属性
        $properties = $obj->getProperties();
        foreach ($properties as $property) {
            $property->setAccessible(true); // 将属性的可访问性设置为 true，从而允许您在类的外部访问和获取这些属性的值
            $propertyName = $property->getName();
            if (in_array($propertyName, $inputKeys)) {
                $this->$propertyName = $inputs[$propertyName];
            }
        }*/

        return $this;
    }
}
